package com.xuecheng.plus.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: xuecheng-online
 * @BelongsPackage: com.xuecheng.plus.base.exception
 * @Author: 枫逸舒
 * @CreateTime: 2023-03-26  09:37
 * @Description: TODO 异常处理类-异常拦截
 * @Version: 1.0
 **/
@Slf4j
@ControllerAdvice       // 增强注解
public class GlobalExceptionHandler {


    /**
     * 对项目自定义异常的处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(XueChengPlusException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorException customException(XueChengPlusException e){
        // 记录异常
        log.error("自定义异常信息：{}", e.getErrMessage(), e);

        // 解析出异常信息
        String errMessage = e.getErrMessage();
        RestErrorException restErrorException = new RestErrorException(errMessage);
        return restErrorException;
    }


    /**
     * 对其他异常的处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorException exception(Exception e){
        // 记录异常
        log.error("系统异常：{}", e.getMessage(), e);

        // 统一抛出“执行过程异常”信息
        RestErrorException restErrorException = new RestErrorException(CommonError.UNKOWN_ERROR.getErrMessage());
        return restErrorException;
    }


    /**
     * 使用异常处理框架，对MethodArgumentNotValidException异常的处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorException methodArgumentNotValidException(MethodArgumentNotValidException e){
        // 得到异常结果
        BindingResult bindingResult = e.getBindingResult();
        List<String> errors = new ArrayList<>();
        // 获取并解析错误信息
        bindingResult.getFieldErrors().stream().forEach((item->{
            errors.add(item.getDefaultMessage());
        }));
        // 拼接错误信息
        String errMessage = StringUtils.join(errors, ",");
        // 记录异常
        log.error("系统异常：{}", e.getMessage(), errMessage);
        // 统一抛出“执行过程异常”信息
        RestErrorException restErrorException = new RestErrorException(errMessage);
        return restErrorException;
    }

}
